package order_list

type MLIST struct {
	MData []interface{}
	MSize int64
	MLen  int64
}

func NewMLIST(size int64) *MLIST {
	return &MLIST{
		MData: make([]interface{}, size),
		MSize: size,
		MLen:  0,
	}
}

func (l *MLIST) IsEmpty() bool {
	return l.MLen == 0
}

func (l *MLIST) IsFull() bool {
	return l.MLen == l.MSize
}

func (l *MLIST) Length() int64 {
	return l.MLen
}

func (l *MLIST) ClearList() {
	l.MLen = 0
	l.MData = make([]interface{}, l.MSize)
}

func (l *MLIST) IndexOf(elem interface{}) int64 {
	var i int64
	for i = 0; i < l.MLen; i++ {
		if l.MData[i] == elem {
			return i
		}
	}
	return -1;
}

func (l *MLIST) GetElem(index int64) (interface{}, bool) {
	if index < 0 {
		return nil, false
	}
	if index > l.MLen-1 {
		return nil, false
	}
	return l.MData[index], true
}

func (l *MLIST) Insert(index int64, elem interface{}) bool {
	if l.IsFull() {
		return false
	}
	if index < 0 {
		return false
	}
	if index > l.MLen {
		return false
	}
	var ii int64
	if index <= l.MLen-1 {
		for ii = l.MLen - 1; ii >= index; ii-- {
			l.MData[ii+1] = l.MData[ii]
		}
	}
	l.MData[index] = elem
	l.MLen++
	return true
}

func (l *MLIST) Delete(index int64) (interface{}, bool) {
	if l.IsEmpty() {
		return nil, false
	}
	if index < 0 {
		return nil, false
	}
	if index > l.MLen-1 {
		return nil, false
	}
	var tempElem = l.MData[index]
	if index < l.MLen-1 {
		var ii int64
		for ii = index; ii < l.MLen-1; ii++ {
			l.MData[ii] = l.MData[ii+1]
		}
	}
	l.MData[l.MLen-1] = nil
	l.MLen--
	return tempElem, false
}

func (l *MLIST) Traverse(callback func(interface{})) {
	var i int64
	for i = 0; i < l.MLen; i++ {
		callback(l.MData[i])
	}
}
